package main

import "sort"

/* 一题双解：枚举、打表二分

#### 方法一：枚举

对于一个数 $x$，我们可以通过统计 $x$ 每个数位的出现次数，记在一长度为 $10$ 的 $\textit{cnt}$ 数组中，并判断 $x$ 每个数位 $d$ 是否满足 $\textit{cnt}[d] = d$，若所有数位均满足，则 $x$ 是一个数值平衡数。

我们可以从 $n+1$ 开始，不断循环往上枚举，判断是否为数值平衡数。

注意到 $1224444$ 是一个数值平衡数，所以我们枚举的上界为 $1224444$，这一计算量是可以接受的。

```go
func nextBeautifulNumber(n int) int {
next:
	for n++; ; n++ {
		cnt := [10]int{}
		for x := n; x > 0; x /= 10 {
			cnt[x%10]++
		}
		for x := n; x > 0; x /= 10 {
			if cnt[x%10] != x%10 {
				continue next
			}
		}
		return n
	}
}
```

#### 方法二：打表 + 二分查找

我们可以按照方法一的算法，计算出 $[1,$1224444$]$ 内的所有数值平衡数，这一共有 $110$ 个，我们将这些数记在 $\textit{balanced}$ 数组中。

然后在 $\textit{balanced}$ 中二分 $n$ 的下一个元素，即为答案。

```go
var balanced = []int{1, 22, 122, 212, 221, 333, 1333, 3133, 3313, 3331, 4444, 14444, 22333, 23233, 23323, 23332, 32233, 32323, 32332, 33223, 33232, 33322, 41444, 44144, 44414, 44441, 55555, 122333, 123233, 123323, 123332, 132233, 132323, 132332, 133223, 133232, 133322, 155555, 212333, 213233, 213323, 213332, 221333, 223133, 223313, 223331, 224444, 231233, 231323, 231332, 232133, 232313, 232331, 233123, 233132, 233213, 233231, 233312, 233321, 242444, 244244, 244424, 244442, 312233, 312323, 312332, 313223, 313232, 313322, 321233, 321323, 321332, 322133, 322313, 322331, 323123, 323132, 323213, 323231, 323312, 323321, 331223, 331232, 331322, 332123, 332132, 332213, 332231, 332312, 332321, 333122, 333212, 333221, 422444, 424244, 424424, 424442, 442244, 442424, 442442, 444224, 444242, 444422, 515555, 551555, 555155, 555515, 555551, 666666, 1224444}

func nextBeautifulNumber(n int) int {
	return balanced[sort.SearchInts(balanced, n+1)]
}
```

*/

// github.com/EndlessCheng/codeforces-go
func nextBeautifulNumber(n int) int {
next:
	for n++; ; n++ {
		cnt := [10]int{}
		for x := n; x > 0; x /= 10 {
			cnt[x%10]++
		}
		for x := n; x > 0; x /= 10 {
			if cnt[x%10] != x%10 {
				continue next
			}
		}
		return n
	}
}

var balanced = []int{1, 22, 122, 212, 221, 333, 1333, 3133, 3313, 3331, 4444, 14444, 22333, 23233, 23323, 23332, 32233, 32323, 32332, 33223, 33232, 33322, 41444, 44144, 44414, 44441, 55555, 122333, 123233, 123323, 123332, 132233, 132323, 132332, 133223, 133232, 133322, 155555, 212333, 213233, 213323, 213332, 221333, 223133, 223313, 223331, 224444, 231233, 231323, 231332, 232133, 232313, 232331, 233123, 233132, 233213, 233231, 233312, 233321, 242444, 244244, 244424, 244442, 312233, 312323, 312332, 313223, 313232, 313322, 321233, 321323, 321332, 322133, 322313, 322331, 323123, 323132, 323213, 323231, 323312, 323321, 331223, 331232, 331322, 332123, 332132, 332213, 332231, 332312, 332321, 333122, 333212, 333221, 422444, 424244, 424424, 424442, 442244, 442424, 442442, 444224, 444242, 444422, 515555, 551555, 555155, 555515, 555551, 666666, 1224444}

func nextBeautifulNumber2(n int) int {
	return balanced[sort.SearchInts(balanced, n+1)]
}
